Reputation: 309
I want to swap the first two lines in all files in a folder and save that over the existing files, keeping file names as before.
What I have:
awk '{getline x;print x}1' *.map.txt
Can this be written only for the first two lines?
What this does is just print in the terminal all the outputs for each file.
Upvotes: 0
Views: 162
Reputation: 24812
You can do it with sed :
sed '1{h;d};2{x;H;x}'
Explanation :
1 and 2 are line number selectors ; the following commands will only be executed on those lines
h puts the current line in the 'hold' buffer
d deletes the line
x swaps the hold buffer with the current line
H appends the current line to the hold buffer
Test run with GNU sed :
$ mkdir test35597922 $ echo """line1 > line2 > line3""" > test35597922/file1.txt $ echo """line1 line2 line3""" > test35597922/file2.txt $ sed -i '1{h;d};2{x;H;x}' test35597922/* $ ls test35597922/ file1.txt file2.txt $ cat test35597922/file1.txt line2 line1 line3 $ cat test35597922/file2.txt line2 line1 line3
If you can't use the 'in place' -i
flag and want to edit the files, you can process as follows :
for file in test35597922/*; do
sed '1{h;d};2{x;H;x}' $file > tmp_file
mv tmp_file $file
done
On some systems it could be done in one action (sed '1{h;d};2{x;H;x}' $file > $file
) but that will fail on others, the file being overwriten before it has entirely been read.
Upvotes: 1
Reputation: 14949
Another sed
:
sed -e '1{N;s/^\(.*\)\n\(.*\)/\2\n\1/;}' file
Use -i
to affect the changes in file.
If you don't have -i
option, try below way.
sed -e '1{N;s/^\(.*\)\n\(.*\)/\2\n\1/;}' file > new_file && mv new_file file
Upvotes: 0
Reputation: 46873
With ed
(and Bash):
for file in ./*; do
[[ -f $file ]] || continue
ed -s "$file" <<< $'1m2\nw\nq\n'
done
The ed
command that does the trick is: 1m2
that selects the first line and moves it to the 2nd line. If you have files with 0 or 1 lines, you'll see some harmless ?
on standard error. You can redirect them to /dev/null
by appending 2> /dev/null
after the done
.
Upvotes: 1