Monday, September 24, 2012

sed pills

# replace empty space with newline

sed -e 's/\s\+/\n/g' old > new
The escape sequence \s matches any whitespace character (space, tab, newline, and so on), so \s\+means a run of one or more whitespace characters to be replaced by a single newline. The /g on the end means perform the substitution as many times as possible rather than just once.
The command above uses the file old as input and writes the modified output to new.
$echo "luca dfg sdfs d sfs fsdflsdfsd " | sed 's@ @_@g'


$echo "luca dfg sdfs d sfs fsdflsdfsd " | sed 's@ @_@'

luca_dfg sdfs d sfs fsdflsdfsd

# wrapping a pattern with stuff

The solution requires the special character "&." It corresponds to the pattern found.

sed 's/[a-z]*/(&)/' new

# remove either open or closed parenthesis

sed "s@\((\|)\)@@g"

Note the construct for the OR rule

# match one or more instances with the +

# remove number

$ echo 'This is a test 12335 and 669384 535xy4' | sed 's/[0-9]*//g'

#Embed a command in a sed line

NATTR=`cat lists/visual/sup/class.txt |wc -l`; 
sed 's@^@'$NATTR'|@'

#Remove empty lines

$ sed  -e '/^$/d'

#Remove the third line

$ sed '3d' fileName.txt

# Remove the interval between lines 7 and 9: 

sed '7,9d' filename.txt 

#Remove first line

$ sed -e '1d' filename.txt

#Remove last line

$ sed -e '$d' filename.txt

#Remove last char of a file

$ sed  -e '$s/,$//'1d

#Pick lines with step 4 starting from line 0, but line zero has nothing so first line printed is 4.

$ sed -n '0~4p' somefile line 4 line 8 $

#Pick lines in an interval

$ sed -n '8,12p'  

#match a number

$ echo  /blablalbl/sdfs-50_am/74321.ext | sed 's@/[0-9]*\.ext@@'

#Replace last occurence of a pattern

$  echo dir1/dir2/dir3/268142.hst | sed -e 's@\(.*\)/@\1/imgs/@'

\1 does the magic, it takes the matching pattern and it replicates in the right part of the rule

No comments:

Post a Comment