Tuesday, September 8, 2015

Substitution inside files by one line bash commands

Recently I searched at the internet for substituing line(s) in many files with increasing number. Here is the example how to substitute whole 3rd line by 'whatever' in the files named  1D*.in.

sed -i '3s/.*/whatever/' > ls 1D*.in 


How to add prefix to every file in the current directory: 

\( for filename in *; do mv "$filename" "'prefix_'$filename"; done; \)

Or eventually rename it:

rename 's/prefix_/a_/' *

or renaming nicer with command mv

\(for file in prefix_* do mv -i "${file}" "${file/prefix_/a_}" done \)

where option -i means 'in-situ'.

Now, let say we want to substitute a string 'cis' to 'fis' in every file
name by bash:

sed -i 's/cis/fis/'

Sed  is a stream editor.  A stream editor is  used to perform basic text transformations on an input stream (a file or input from a pipeline).  By default, sed sends its results to the screen. You can cancel this default printing with option -n.
Syntax: sed [options] 'commands' [file-to-edit] For commands use ampersands, like e.g.
sed '3d' - to delete the 3rd line
sed -n '2p' -to print the 2nd line and shut down the default printing on the screen by option -n. Otherwise it will print a line two times.
sed -n '/root/p' -to print only the matching line and shut down the default printing on the screen by option -n

sed -i --in-place[=SUFFIX]
 edit files in place (makes backup if SUFFIX supplied) - the files will be rewritten.

sed 's/to_be_replaced/replacement/' - if match, replace a string by a string with replacement string.

Regular characters for sed:

$    the end of line
^    the start of line
.*   everything on line
\n   new line break
$!   last line

To join more commands you can use either -e option
sed -i -e '3s/to_be_replaced/replacement/' -e '2d' *.m
or with semicolon
sed -i '3s/to_be_replaced/replacement/' ; '2d' *.m

My special thanks belongs to guys on Stackoverflow and creators of man pages for Linux.

No comments:

Post a Comment