Get Specific Line from Text File Using Just Shell Script

Get specific line from text file using just shell script

sed:

sed '5!d' file

awk:

awk 'NR==5' file

go to a specific line of a text file by shell script

You could use the tail utility. By default, it outputs the last 10 lines of a file, but it also has some quite useful parameters. To skip the first X lines, use -n+X.

Example:

 tail -n+5 myfile.txt

will output the whole file from the 5th line (skipping the first 4).

But in your case, you could simply increment a variable to start the processing on line 4. Example:

l=0 
while read compareFile1 <&3 && read compareFile2 <&4; do
if [[ $l < 4 ]]; then
l=$((l+1));
else
# do your processing here
echo $compareFile1
echo $compareFile2
fi
done 3<test1.txt 4<test2.txt

Bash tool to get nth line from a file

head and pipe with tail will be slow for a huge file. I would suggest sed like this:

sed 'NUMq;d' file

Where NUM is the number of the line you want to print; so, for example, sed '10q;d' file to print the 10th line of file.

Explanation:

NUMq will quit immediately when the line number is NUM.

d will delete the line instead of printing it; this is inhibited on the last line because the q causes the rest of the script to be skipped when quitting.

If you have NUM in a variable, you will want to use double quotes instead of single:

sed "${NUM}q;d" file

Linux - How to get a string specific string from a specific line?

With a simple command you can solve it. grep test3\.zip DeletedFiles.txt

Get specific lines from a text file

grep -A $NUM

This will print $NUM lines of trailing context after matches.

-B $NUM prints leading context.

man grep is your best friend.

So in your case:

cat log | grep -A 3 -B 3 FAIL

How can replace a specific line in a text file with a shell script?

Using sed and backreferencing:

sed -r '/bladeServerSlot/ s/(^.*)(=.*)/\1=12/g' inputfile

Using awk , this will search for the line which contains bladeServerSlot and replace the second column of that line.

awk  'BEGIN{FS=OFS="="}/bladeServerSlot/{$2=12}1' inputfile


Related Topics



Leave a reply



Submit