How do I replace a space " " character at a particular position in a line?
e.g. I have a file below
$ cat i2
111 002 A a
33 0011 B c
2222 003 C a
I want all the 1st spaces to be replaced with forward slash "/" and the 3rd spaces to have 5 spaces to get the output below:
111/002 AAA a
33/0011 BBB c
2222/003 CCC b
I created a shell which would achieve this but I'm looking for a easier way.
$ cat test.ksh
#!/bin/ksh
cut -d' ' -f1 < $1 > 1st_word
cut -d' ' -f3 < $1 > 3rd_word
while read line
do
sed -e "s/$line /$line\//g" $1 | grep $line
done < 1st_word > tmp_ouput
while read line
do
sed -e "s/$line /$line /g" tmp_ouput1 | grep $line
done < 3rd_word
Any help will be appreciated
Steve
anbu23
March 29, 2007, 2:31am
2
$ cat file
111 002 A a
33 0011 B c
2222 003 C a
$ sed -e "s; ;/;1" -e "s/ / /2" file
111/002 A a
33/0011 B c
2222/003 C a
Try this..
sed -e 's/ /\//' -e 's/\(.* .*\)\( .*\)/\1 \2/' filename
Output:
cat temp
111 002 A a
33 0011 B c
2222 003 C a
sed -e 's/ /\//' -e 's/\(.* .*\)\( .*\)/\1 \2/' temp
111/002 A a
33/0011 B c
2222/003 C a
Depending on your version of sed something like this may work for you:
$ sed -e 's! !/!1' -e 's/ / /2' infile > outfile
If that doesn't work, the "longhand" version will....
$ sed -e 's/^\([^ ]*\) \([^ ]*\) \([^ ]*\) \(.*\)$/\1\/\2 \3 \4/' infile > outfile
Cheers
ZB
sed 's/ /\//;s/ \(.\)$/ \1/' file
That's exactly what I wanted!
Thank you all for your quick response!!!
Cheers
Steve
sed 's/ /\//;s/ \(.\)$/ \1/' file
Hi matrixmadhan, can you explain what mean your code?
Thank you
regards,
heru
stevefox:
How do I replace a space " " character at a particular position in a line?
e.g. I have a file below
$ cat i2
111 002 A a
33 0011 B c
2222 003 C a
I want all the 1st spaces to be replaced with forward slash "/" and the 3rd spaces to have 5 spaces to get the output below:
111/002 AAA a
33/0011 BBB c
2222/003 CCC b
[...]
printf "%s/%s %s%5s\n" $(<inputfile)
following are the blocks in the code,
s/ /\// - this first substitution block replaces the first occuring space character to a forward slash, since thats a special character to nullify its special meaning precede it by a back slash
s/ \(.\)$/ - the second substitution block replaces the space and any character at the end with the below replacement below
\\1/ - this would effectively replace it with 5 spaces and the selected block