1

I want to add $x/ from data formatted as $x-xyz (xyz is a mix of text and number to be ignored).

Example data

AB-10C
CD-02E

Output

AB/AB-10C
CD/CD-02E

How do I describe the variable as text before the hyphen? My idea is:

define $x = # don't know how to do that
## and then somehow use sed to prepend
sed -i s/$/$x/ file
# I don't know if sed can handle variables though - the above one liner is from Googling
5

Here's a quick and dirty awk version:

awk -F- '{print $1"/"$0}' input_file > output_file

What it does is use - as a field separator, and prints the first column (i.e. everything before the first -), then a /, then the whole original line.

A way of doing the same thing with sed would be:

sed -e 's;^\([^-]*\)\(.*\);\1/\1\2;' input_file > output_file

(but that's hardly readable.)

If you want to do it in plain bash, you can use string manipulations:

$ foo=AB-10C
$ prefix=${foo%%-*}
$ echo ${prefix}/${foo}
AB/AB-10C

Use that in a while read loop or similar if the data is coming from a file.

  • Though it was unintentional, I simplified the example a bit, and the results with the real data were interesting. The actual data was like 211,AB-45A,1, and it got manipulated to 211,AB/211,AB-45A,1 with both awk and sed. Couldn't try pure bash since I'm not quite familiar with while read and didn't bother researching. Anyway, I separated the relevant data and it worked as expected - thank you! – Oxwivi Jan 29 '12 at 14:19
  • For the while loop, just type "[bash] while read" in the search box at the top of this site. You'll get plenty of examples :) – Mat Jan 29 '12 at 14:21
0

This might work for you:

echo -e "123,AB-10C,4\n567,CD-02E,8" |
sed 's|\([^,]*\)-.*|\1/&|'
123,AB/AB-10C,4
567,CD/CD-02E,8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.