0

I have bunch of CSV files named like so in a directory:

 s_m_u_supplemental_fields_account_9_4_2015_11_26_Error.csv
 s_m_u_supplemental_fields_account_9_4_2015_12_3_Error.csv
 s_m_u_academic_status_loa_8_29_2015_0_1_Error.csv

I need to capture the "s_m_u_academic_status_loa" part to append to a column inside the file. I tested the expression "s/^\(s_([^_0-9]+_)+\)\([^\.]+\.csv\)$/\1/" in RegEx Tester online and does capture what I need, but for some reason it fails to work from AIX ksh.

Here is my script so far (AIX 6.2):

#!/bin/ksh

ls *_Error.csv | while read i
do
    echo ${i}
    edfilename = `echo ${i} |sed -e "s/^\(s_([^_0-9]+_)+\)\([^\.]+\.csv\)$/\1/"`
    echo ${edfilename}
done
  • 1
    there must be no spaces around "=" when doing variable=value assignment – meuh Sep 7 '15 at 19:08
  • 1
    I'd also strongly recommend you double quote your variables when you use them. For example echo "$edfilename" instead of just echo $edfilename. – roaima Sep 7 '15 at 19:16
1

You might try this version of your script so far

#!/bin/ksh
ls *_Error.csv | while read i
do  echo "${i}"
    edfilename=$(echo "${i}" | sed -e 's/^\(s_([^_0-9]*_)*\)\([^\.]*\.csv\)$/\1/')
    echo "${edfilename}"
done

I dont think aix sed understands + so I've replaced them with *. If you really need + then use \{1,\} which may work on aix.

A simpler pattern that should suffice: 's/\([^0-9]*\)_.*/\1/'

  • Thanks @meuh The simplified pattern works. I didn't realize AIX doesn't like +! – sleepy bubba Sep 7 '15 at 23:01
  • Arrrgghhh!  Don't parse the output of ls; just do for i in *_Error.csv. – Scott Sep 8 '15 at 6:01
  • @Scott I prefer to minimise changes to an OP script to avoid problems in case they have reduced their code just to expose their difficulty. For example, ls and pipe will act differently if the glob finds no matching files. A for loop would need shopt -s nullglob to work the same way. – meuh Sep 8 '15 at 7:56
  • Using ls -d would stop descent into directories (if present). A change of atom+ to atom* should really become atom atom* to ensure that at least one applies. – roaima Sep 8 '15 at 10:55

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.