0

I would like to modify the end part of a file name in a script like the following

    #!/bin/bash
    file = ...
    gawk -f shc2csv.awk $1 > $file.csv

where $1 is typically something like shc_20210901_0002_763803214.html and file should be shc_20210901.

So the string should be cut from the second _.

How shall I obtain file from $1 with sed or awk?

1 Answer 1

3

You do not need sed or awk to modify a value in a variable $1.

#!/bin/bash

file=${1%_*}    # remove the part after the last `_`
file=${file%_*} # repeat the removal to the second `_`

gawk -f shc2csv.awk "$1" > "$file".csv

You should quote variable expansions.

3
  • OK, thank you. I was expecting some fancy one-liner sed or awk, but I forgot indeed that bash also has string operators.
    – macxpat
    Aug 26, 2021 at 2:58
  • nice.. also with bash extglob (extended globs) - echo ${file%_+([!_])_+([!_])}
    – iruvar
    Aug 26, 2021 at 4:30
  • @iruvar Or we could call a regex: [[ $1 =~ ^(.*)_([^_]+)_([^_]+)$ ]] && file="${BASH_REMATCH[1]}"
    – user232326
    Aug 26, 2021 at 5:28

You must log in to answer this question.

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