Reputation: 583
I have a file that needs a semicolon delimiter after the first field, which is 4 or 5 characters in length. I tried using sed (modified a sed script I found) and it was an epic fail...it inserted semicolons between every character. I just need to add a semicolon to the end of the first field.
Here is some example text:
2A19 kRSUnicode 205.8
2FA1A kRSUnicode 206.2
2FA1B kRSUnicode 207.5
And the output I'm hoping for:
2A19; kRSUnicode 205.8
2FA1A; kRSUnicode 206.2
2FA1B; kRSUnicode 207.5
Anyone know how to do this? Thank you!
Upvotes: 2
Views: 9548
Reputation: 831
Tabs and spaces are known as whitespace. This will replace the first character of whitespace with a semicolon:
sed 's/[[:space:]]/;/'
# or
sed 's/[[:space:]]/; /' # preserves the space char.
This will replace the first instance of all whitespace with a semicolon:
sed 's/[[:space:]]\{1,\}/;/'
This will replace all instances of whitespace with a semicolon:
sed 's/[[:space:]]\{1,\}/;/g'
# or
tr '\t ' ';'
Upvotes: 4
Reputation: 7812
Here is a shell only method: It wasn't 100% clear on whether the first delimiter space was a tab or a variable number of spaces, so I just used echo to squeeze them all into 1 space here
FILE="tmpfile"
OUTPUT=""
while read LINE || [ "$LINE" ]; do
LINE=`echo $LINE`
OUTPUT="${OUTPUT}${LINE/ /; }
"
done < "${FILE}"
echo "${OUTPUT}" > "${FILE}"
or if it is in fact a single tab, simply:
...
while read LINE || [ "$LINE" ]; do
OUTPUT="${OUTPUT}${LINE/ /; }
"
done < "${FILE}"
...
Upvotes: 0
Reputation: 77155
sed 's/\(\s\+\)/;\1/' file
Based on the Input Data, you can match the first tab and add ;
before it.
[jaypal:~/Temp] cat file
2A19 kRSUnicode 205.8
2FA1A kRSUnicode 206.2
2FA1B kRSUnicode 207.5
[jaypal:~/Temp] sed 's/\(\s\+\)/;\1/' file
2A19; kRSUnicode 205.8
2FA1A; kRSUnicode 206.2
2FA1B; kRSUnicode 207.5
Upvotes: 0
Reputation: 140427
If you don't care about anything after the semi-colon, this is even more trivial with awk
$ awk '$0=$1";"' infile
2A19;
2FA1A;
2FA1B;
This is trivial with awk
awk '$1=$1";"' OFS='\t' infile
$ awk '$1=$1";"' OFS='\t' infile
2A19; kRSUnicode 205.8
2FA1A; kRSUnicode 206.2
2FA1B; kRSUnicode 207.5
Upvotes: 2
Reputation: 8540
you can loop below sed command for every line
echo "abcde I am a good boy" |sed -e 's/ /:/'
Upvotes: 0
Reputation: 37298
It really helps to include sample data and output in your question, but based on what you have said, the following will work
# replace the first space in a line with a semicolon.
printf "sample data1, data2 data3\n" \
| sed 's/ /;/'
Produces the output
sample;data1, data2 data3
you can process whatever file you have with
sed 's/ /;/' file > newFile
Or if your using Linux with GNU sed
sed -i 's/ /;/' file
I hope this helps.
Upvotes: 0