Given a file with data like this (ie stores.dat file)
id storeNo type
2ttfgdhdfgh 1gfdkl-28 kgdl
9dhfdhfdfh 2t-33gdm dgjkfndkgf
Desired output:
id |storeNo |type
2ttfgdhdfgh |1gfdkl-28 |kgdl
9dhfdhfdfh |2t-33gdm |dgjkfndkgf
Would like to add a “|” delimiter between each of these 3 cut ranges:
cut -c1-18,19-30,31-40 stores.dat
What is the syntax to insert a delimiter between each cut?
BONUS pts (if you can provide the option to trim the values like so):
id|storeNo|type
2ttfgdhdfgh|1gfdkl-28|kgdl
9dhfdhfdfh|2t-33gdm|dgjkfndkgf\
UPDATE (thanks to Mat’s answer) I ended up with success on this solution – (it is a bit messy but SunOS with my bash version doesn’t seem to support more elegant arithmetic)
#!/bin/bash
unpack=""
filename="$1"
while [ $# -gt 0 ] ; do
arg="$1"
if [ "$arg" != "$filename" ]
then
firstcharpos=`echo $arg | awk -F"-" '{print $1}'`
secondcharpos=`echo $arg | awk -F"-" '{print $2}'`
compute=`(expr $firstcharpos - $secondcharpos)`
compute=`(expr $compute \* -1 + 1)`
unpack=$unpack"A"$compute
fi
shift
done
perl -ne 'print join("|",unpack("'$unpack'", $_)), "\n";' $filename
Usage: sh test.sh input_file 1-17 18-29 30-39
If you’re not afraid of using perl, here’s a one-liner:
The
unpackcall will extract one 17 char string, then a 12 char one, then a 10 char one from the input line, and return them in an array (stripping spaces).joinadds the|s.If you want the input columns to be in
x-yformat, without writing a “real” script, you could hack it like this (but it’s ugly):Usage:
t.sh 1-17 18-29 30-39 input_file.