Bash delete/modify line from a file -


lets have file contacts.txt in format

number1:name1:phone1:adress1 number2:name2:phone2:adress2 

the question how can delete line(contact) file or modify of components of contact? delete line thought of using this

grep -ve "name1" 

and overwrite entire file im sure there better way this...

since data appears colon-delimited, obvious tool handle awk.

simple sed approaches have disadvantage treat input plain text, not yield desired result. if, example, have mr. smith , mrs. doolittle lives in smithy place 23, removing lines contain "smith" remove mrs. doolittle along mr. smith.

awk, on other hand, splits line fields can tests on fields individually. example, remove mr. smith file, use

awk -f : '$2 != "smith"' myfile.txt 

where $2 stands second field, making call select lines second field "smith". -f : sets input field separator colon rather default whitespace, lines in file split @ colons.

it allows straightforward modification. register mr. smith's new phone number, example, might use

awk -f : 'begin { ofs = fs } $2 == "smith" { $3 = "555-123456" } { print }' myfile.txt 

here ofs output field separator; set same input field separator in beginning output colon-delimited input. rest should self-explanatory -- if second field "smith", third set "555-123456", , regardless of whether transformation happened (because there no attached condition), line printed1.

for in-place editing, need gnu awk 4.1.0 or later (add -i inplace option call), since desirable have backup in case things go wrong, i'd use

cp myfile.txt myfile.txt~ awk ... myfile.txt~ > myfile.txt 

or so.

you can find useful awk tutorial here.

1 actually, instead of { print } more common write shorter 1 (which, non-zero value, means true when treated condition). how works explained in tutorial; in short: action without condition executed unconditionally, , condition without action performs default action (printing) if condition true. put in { print } because less confusing beginner's eye.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -