Tuesday, October 25, 2022

[SOLVED] Delete lines in a file that start with specific strings

Issue

I have some files that look like this:

Node   Present
1   243
2   445
10  65
4  456
43  8
...

I need to remove the values corresponding to specific nodes and I have a file specifying this nodes that looks like this:

1
4
...

The idea is to delete the lines that start with the values specified in my second file. I know that "sed" can do something like this, but I do not know how to apply it for all the values specified in the second file. More over, I want to delete node 1, but not node 100, and I am seeing that node 100 will also get erased with my approach.

sed '/^1/d'

Solution

sed is not the right tool for this job. I suggest using awk like this:

awk 'NR == FNR {ids[$1]; next} NR == 1 || !($1 in ids)' ids nodes

Node   Present
2   445
10  65
43  8

Where input files are:

cat ids
1
4

cat nodes
Node   Present
1   243
2   445
10  65
4  456
43  8


Answered By - anubhava
Answer Checked By - Timothy Miller (WPSolving Admin)