0

I'm trying to copy a file but skip a specific line in the file that starts with 'An', using the bash in mac terminal.

The file only has 4 lines:

Kalle Andersson    036-134571
Bengt Pettersson   031-111111
Anders Johansson   08-806712
Per Eriksson       0140-12321

I know how to copy the file using the command cp and to grab a specific line in the file using the grep command. I do not know how i can delete a specific line i the file.

I have used the cp command:

cp file1.txt file2.txt

to copy the file.

And I used the

grep 'An' file2.txt

I expect the result where the new file have the three lines:

Kalle Andersson   036-134571
Bengt Pettersson  031-111111
Per Eriksson      0140-12321.

Is there an way I can do this in a single command?

oguz ismail
  • 1
  • 16
  • 47
  • 69

1 Answers1

2

As Aaron said:

 grep -vE '^An' file1.txt > file2.txt

What you do here is use grep with the -v option. That means print every line, except the one that matches. Furthermore, you instruct the shell to redirect the output of the grep to file2.txt. That is the meaning of the>.

There are a lot of commands in Unix/Linux that can be used for this. sed is an obvious candidate, awk can do it, as in

awk '{if (!/^An/) print}' file1.txt > file2.txt

Another option is ed:

ed file1.txt <<EOF
1
/^An
d
w file2.txt
q
EOF
Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31