Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash substring with regular expression

In a bash script, I´d like to extract a variable string from a given string. I mean, i´d like to extract the string file.txt from the string:

This is the file.txt from my folder.

I tried:

var=$(echo "This is the file.txt from my folder.")
var=echo ${var##'This'}
...

but I´d like to make it in a cleaner way, using the expr, sed or awk commands.

Thanks

Edited:

I found another way (nevertheless, the answer with the sed command is the best one for me):

var=$(echo 'This is the file.txt from my folder.')
front=$(echo 'This is the ')
back=$(echo ' from my folder.')
var=${var##$front}
var=${var%$back} 
echo $var
like image 268
Luis Andrés García Avatar asked Oct 14 '13 08:10

Luis Andrés García


People also ask

How do I cut a string in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How do I extract a string from a word in bash?

If "name=foo" is always in the same position in the line you could simply use: awk '{print($3)}' , that will extract the third word in your line which is name=foo in your case. He told "also other parameters may or may not be there" hence you may not use a positional logic.

How do you slice a string in Linux?

The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text.


1 Answers

The following solution uses sed with s/ (substitution) to remove the leading and trailing parts:

echo "This is the file.txt from my folder." | sed "s/^This is the \(.*\) from my folder.$/\1/"

Output:

file.txt

The \( and \) enclose the part which we want to keep. This is called a group. Because it's the first (and only) group which we use in this expression, it's group 1. We later reference this group inside of the replacement string with \1.

The ^ and $ signs make sure that the complete string is matched. This is only necessary for the special case that the filename contains either "from my folder." or "This is the".

like image 184
Daniel S. Avatar answered Sep 28 '22 04:09

Daniel S.