1

I store files named like this: word-word2-word3-word4.txt . The number of "words" varies from file to file.

I want to replace certain of the dashes with pluses e.g word+word2-word3+word4.txt

I want to specify the dashes or minus-signs to change by typing in numbers.

I have an awkward script that doesn't work - it does this:

  • dashes are supplemented with a semi-colon for later awk splitting purposes
  • user types in numbers specifying dashes to replace
  • numbers are appended to end of filename e.g aaa-;bbb-;ccc.txt 1 3
  • and piped into awk for processing
  • in awk, make an array of the appended numbers,
  • and an array of the words with a split on the first field
  • then gsub ';' for '+' on the split array using the number array to specify the index

Here is my grisly script which hardcodes the filename for the purposes of quick fiddling and trialing. I can't think how to exit the awk script usefully. The plan is to exit awk and do a final substitution in sed.

I am quite aware this is a dogs dinner of a script displaying plenty of poor-learning. Nevertheless, please offer any help if you are disposed to.

file='wot-;wit-;wet-;wat.txt'; 
echo -n "type digits"; 
read nos; varr=$(echo $nos); 
newfile=$(echo $file $varr); 
echo "$newfile" | awk '{ for (i=2; i<=NF ;i++) arr[i]=$i}
                         END{ split($1,spl,"-");
                              for( var in arr ) gsub(";","+", spl[var]); 
                              print THIS IS NOT WORKING - CAN'T GET ANYTHING USEFUL OUT }'

1 Answer 1

1

I have no idea about awk, however I know the way with shell+sed:

file='wot-;wit-;wet-;wat.txt'; 
echo -n "type digits : "; 
read nos; 
# this is used to sort numbers in order, otherwise the script
# will work only when user specifies numbers in right order
# also we delete all non-numbers string to make sed code safe enough
nos="$(echo $nos|tr ' ' '\n'|sort -n|grep -v '[^0-9]'|tr '\n' ' ')"
# here we build sed code and modify the text
echo "$file" | { for i in $nos ; do A="s/-/+/$i;$A" ; done ; sed "$A" ; }
2
  • That works, thx. I don't quite get the last line of your script, in particular the recursive use of $A. Bash loops thru numbers stored in $nos. Each loop writes out a substitution. When the loop finishes, run the final sed which, for two numbers, is a sequence of 2 consecutive sed operations starting with the last one, and ending w the first one...(?)
    – Tom
    Commented Nov 20, 2012 at 15:17
  • Yes, that's right.
    – rush
    Commented Nov 20, 2012 at 18:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .