-
Useful commands using sed.
- sed (stream editor)
-i
-- in place text editings
-- the substitute commandg
-- global (replace all occurrence)original
-- original textnew
-- new text
sed -n '/test1/,/test2/p' file.txt
-
In found lines search strings will be included.
-
To exclude search strings
sed -n '/test1/,/test2/{/test1/b;/test2/b;p}' file.txt
sed -i '/original/c\new' file.txt
sed -i 's/original/new/g' file.txt
sed -i "s/$original/new/g" file.txt
- NOTE:
"
is used instead of'
. - NOTE:
$original
means env variable is used.
$original
can be used with Bash parameter expansion trick which allows you to use default value if env variable is not set. For example
original="${ORIGINAL_ENV:-default_value}"
Let's assume ORIGINAL_ENV
is not set, original variable will end up with having default_value
.
sed -i "s|$original|new|g" file.txt
echo "a,b" | sed 's/,/\n/g'
echo "a/b" | sed 's/\//\n/g'
echo "a b" | sed 's/\s/\n/g'
echo "a b" | sed 's/\s\+/\n/g'
echo "a b" | sed 's/\s\+/\n/g'
echo " a b" | sed -e 's/^[ \t]*//'
echo " a b" | sed -e 's/^[ \t]*//'
echo "a b " | sed -e 's/[[:space:]]*$//'
echo "a b " | sed -e 's/[[:space:]]*$//'
:space
-- Use posix standard to specify space which will handle tabs too.
sed -i '/^string/d' file.txt