Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the first part of a string in Bash?

Tags:

This code will give the first part, but how can I remove it and get the whole string without the first part?

echo "first second third etc"|cut -d " " -f1
like image 714
Hard Rain Avatar asked Dec 09 '12 14:12

Hard Rain


People also ask

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

Using the parameter expansion syntax To remove the first and last character of a string, we can use the parameter expansion syntax ${str:1:-1} in the bash shell.

How do I trim a string in bash?

Example-2: Trim string data using `sed` commandUse sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command. The following commands removed the spaces from the variable, $Var by using `sed` command and [[:space:]]. $ echo "$Var are very popular now."

How do I remove a prefix in bash?

Since we're dealing with known fixed length strings ( prefix and suffix ) we can use a bash substring to obtain the desired result with a single operation. Plan: bash substring syntax: ${string:<start>:<length>} skipping over prefix="hell" means our <start> will be 4.


2 Answers

You can use substring removal for that. There isn't any need for external tools:

$ foo="a b c d"
$ echo "${foo#* }"
b c d
like image 32
Mat Avatar answered Sep 20 '22 13:09

Mat


You should have a look at info cut, which will explain what f1 means.

Actually we just need fields after(and) the second field. -f tells the command to search by field, and 2- means the second and following fields.

echo "first second third etc" | cut -d " " -f2-
like image 185
sleepsort Avatar answered Sep 20 '22 13:09

sleepsort