Thursday, January 31, 2019

How to get input and make output to the same file on Linux

There can be several options. Suppose we have text file a, filled up with literal 'a', and our objection is change its contents to 'b', in other words replace every 'a' to 'b'

1. Using GNU sed to edit file in place (with backup of file a applying extension [SUFFIX] to name):

# sed -i[SUFFIX] 's/a/b/g' a

or without backup of file a :

# sed -i 's/a/b/g' a

P.S. On Solaris, it's possible to use gsed instead of sed

2. Using interim file :

# sed 's/a/b/g' a > interim_file && mv interim_file a

3. Playing with file descriptors. One possible variant is :

# exec 3<>a && sed 's/a/b/g' a >&3 && exec 3<&-

4. Using shell process substitution :

# sed 's/a/b/g' a > >(sleep 1 && cat > a)

Sleep is necessary to make some interval after sed finish its work

5. Many other alternatives, using ed, cat&echo etc.

Good Luck !