Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I strip first X characters from string using sed?

Tags:

bash

shell

sed

I am writing shell script for embedded Linux in a small industrial box. I have a variable containing the text pid: 1234 and I want to strip first X characters from the line, so only 1234 stays. I have more variables I need to "clean", so I need to cut away X first characters and ${string:5} doesn't work for some reason in my system.

The only thing the box seems to have is sed.

I am trying to make the following to work:

result=$(echo "$pid" | sed 's/^.\{4\}//g')

Any ideas?

like image 990
Kokesh Avatar asked Oct 12 '22 19:10

Kokesh


People also ask

How do I remove the first 10 characters from a string in Unix?

Removing the first n characters To remove the first n characters of a string, we can use the parameter expansion syntax ${str: position} in the Bash shell.

How do I remove the first character of a string in bash?

To remove the first and last character of a string, we can use the parameter expansion syntax ${str:1:-1} in the bash shell. 1 represents the second character index (included). -1 represents the last character index (excluded). It means slicing starts from index 1 and ends before index -1 .


2 Answers

The following should work:

var="pid: 1234"
var=${var:5}

Are you sure bash is the shell executing your script?

Even the POSIX-compliant

var=${var#?????}

would be preferable to using an external process, although this requires you to hard-code the 5 in the form of a fixed-length pattern.

like image 221
chepner Avatar answered Oct 17 '22 18:10

chepner


Here's a concise method to cut the first X characters using cut(1). This example removes the first 4 characters by cutting a substring starting with 5th character.

echo "$pid" | cut -c 5-
like image 142
Randy the Dev Avatar answered Oct 17 '22 17:10

Randy the Dev