Quoting through a file and deleting certain lines

I want to iterate over a file and delete certain lines. Example file:

test.txt

a b c d 

What I have:

 FILE=/tmp/test.txt while read FILE do # if the line starts with b delete it otherwise leave it there ? done 
+4
source share
4 answers

This is the job for sed - the UNIX thread editor:

 (sed '/^b/d' yourfile > yourfile~ && mv yourfile~ yourfile) || rm yourfile~ 

The command will delete all lines starting with b and write the rewrite lines to the backup file. If this succeeds, the backup file will be renamed to the original file; if it fails, the backup file will be deleted.

+8
source

you can do it with grep oneliner:

 grep -v "^b" test.txt > newfile 
+4
source

Easily executed with bash built-in functionality:

 while read -r; do [[ $REPLY = b* ]] || printf '%s\n' "$REPLY" done <file >file.new mv file.new file 
+2
source

"Perl ... it could be in your $PATH " $PATH

Using $SHELL for tiny text tasks (ie sh , ksh , zsh , bash , tcsh , csh ) on BSD, OSX, Linux, AIX, Solaris with various "standard POSIX" compared to BSD, Linux and GNU extensions to sed , grep and other utilities and taking care of accounting for gawk compared to awk and older versions of tools on many server systems ... can be difficult.

 perl -i.orig -ne 'print unless /^b/' test.txt 

Did it work?

 diff test.txt test.txt.orig 
0
source

Source: https://habr.com/ru/post/1489929/


All Articles