Difference between revisions of "Linux command: sed"

From RHS Wiki
Jump to navigation Jump to search
Line 25: Line 25:
 
== Replace New Line (\n) with ", " ==
 
== Replace New Line (\n) with ", " ==
 
  sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/", "/g'
 
  sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/", "/g'
 +
 +
== Uppercase to lowercase ==
 +
sed 's/.*/\L\1/g' < input

Revision as of 22:11, 25 December 2017

The sed command can be used for varius things see man page:
sed command man page
An example of use of sed to replace characters:
echo <string to replace> | sed <regular expression>
Regular expresion:

s -> replace.
g -> all the 'e' are replaced with 'R'. without g only one 'e' is replaced.
# -> delimitation character can be: {|, /, #}.

Example:

echo "esto es un ejemplo" | sed 's#e#R#g'

Replace New Line Characters

sed ':a;N;$!ba;s/\n/ /g'

This will read the whole file in a loop, then replaces the newline(s) with a space.
Explanation:
Create a label via :a.
Append the current and next line to the pattern space via N.
If we are before the last line, branch to the created label $!ba ($! means not to do it on the last line as there should be one final newline).
Finally the substitution replaces every newline with a space on the pattern space (which is the whole file).

Here is cross-platform compatible syntax which works with BSD sed (as per @Benjie comment):

sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g'

Replace New Line (\n) with ", "

sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/", "/g'

Uppercase to lowercase

sed 's/.*/\L\1/g' < input