Home > Blockchain >  I wanted to extract a specific word from a file using linux commands
I wanted to extract a specific word from a file using linux commands

Time:12-29

I wanted to extract a specific word from a file using linux commands. Below is the content of my file

DVC Version Tag: Engine-4.0.1

I wanted to extract "Engine-4.0.1" from the above content of a file to a variable. I tried

sed -n '/Engine/p' dvc_version_text.txt

This print the entire line. My expected output is to print only Engine-4.0.1

CodePudding user response:

I threw your text into my own test.txt file and was able to get exactly what you needed from it using

sed 's/[^:]*: *//' test.txt -> Engine-4.0.1

CodePudding user response:

Below awk should work:

awk -F ': ' '/^DVC Version Tag/{print $2}' file.txt

Output:

Engine-4.0.1

Using GNU sed:

sed -E 's/^DVC Version Tag:\s*//' file.txt

OR

sed -E '/DVC Version Tag:/s/^.*:\s*//' file.txt

Output:

Engine-4.0.1

CodePudding user response:

Since the content of your file, according to your definition, consists solely of this line, you can simply do a

awk '{ print $NF }' <dvc_version_text.txt

or

cut -d ' ' -f 4 <dvc_version_text.txt

or

grep -oE 'Engine. '  <dvc_version_text.txt

CodePudding user response:

Assuming:

  • You want to find the word starting with Engine in the file.
  • There are no extra strings after the word in the line.
  • There may be other lines which do not contain Engine.

Then would you please try:

sed -En 's/.*(Engine.*)/\1/p' dvc_version_text.txt

CodePudding user response:

If the needed string always occurs after the final space, this sed will work

$ sed 's/.*\s//' input_file
Engine-4.0.1

CodePudding user response:

bash

X=$( echo DVC Version Tag: Engine-4.0.1 | cut -d ' ' -f4 )
X=$( echo DVC Version Tag: Engine-4.0.1 | cut -d ':' -f2 )

CodePudding user response:

You can use the given below command.

grep "Engine-4.0.1" filename | awk -F":" '{print $2}'

CodePudding user response:

We can use grep.

grep <location> -ie <pattern> | awk -F":" '{print$2}'

We'll provide a couple of arguments:

location → location of your file,

pattern → In our case Engine

  • Related