How to extract patterns form a text files in shell

2020-04-17 05:23发布

问题:

I have a text file that contains:

toto.titi.any=val1
toto.tata.any=val2
toto.tete.any=val2

How to extract titi , tata and tete from this file.

Should be some sthing like that

$ cat myfile.txt | sed '......' 

and the output should be

titi
tata
tete

回答1:

Do you really need sed? You could use cut:

cut -d. -f2 filename


回答2:

With awk you can do:

awk -F. '{print $2}' file


回答3:

awk/cut would be better choice for this problem.

here is the sed line and grep option:

sed -r 's/.*\.([^.]*)\..*/\1/'
grep -Po '\.\K[^.]*(?=\.)' 


回答4:

awk and cut are best for this

you can also read the file line by line, and print out the portion needed.

$ IFS=.
$ while read first interested others ; do echo $interested; done < file
titi
tata
tete


回答5:

sed -n 's/^[^.]*.\([^.]*\)..*/\1/p' myfile.txt

display second value between dot from line having at least 2 dot inside