0

I have few files that I need to extract from the file extension and remove the number at the end of each file

test1.alarms
abcd1.alarms
test2.alarms
abcd2.alarms

Below is the code I used. The first part worked which removed the file extension and inserted back into the file, however, I was not able to remove the number of each file. After obtaining the result, I would then insert that back into the file.

for f in *.alarms; do
base=$(basename "$f" '.alarms')
sed --i "s/^/$base\:/" $f
db_name=`echo $base | grep -o [a-z]`
sed -ie "s/^/$db_name\:/" -i $f
done

result should be

test
abcd
test
abcd
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
LNL
  • 5
  • 2
  • `remove the number at the end of each file` - you want to `mv` the file? Right now your script tries manipulates the content of the file, not the filename, dunno, is this intentional? – KamilCuk Jul 30 '19 at 18:44
  • 1
    How about `db_name=$(echo $f | sed 's/[0-9]\.alarms$//')`? – joanis Jul 30 '19 at 18:48
  • The dot has no special significance. If you want to remove `[0-9].alarm` then, well, do that. `basename` can't do it alone but the duplicate shows how to do various pattern substitutions (and then you don't need `basename` at all). – tripleee Jul 31 '19 at 08:24

2 Answers2

2

How about a single line solution:

printf '%s\n' *.alarms | sed 's/[[:digit:]]*\.alarms$//g'

When printf receives more arguments than values formats, it repeats the format string for each extra argument:

printf '%s\n' *.alarms: will expand all file names matching the globbing pattern *.alarms into an argument per file name.

The %s\n format string will cause each file name argument to be printed with a new-line character \n, effectively producing a newline delimited list of file-names, matching the *.alarms pattern.

This method is preferred to the unreliable parsing of an ls's command output.

Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • 2
    Perhaps you should explain why you prefer `printf` over `ls`. Maybe see also https://mywiki.wooledge.org/ParsingLs – tripleee Jul 31 '19 at 08:22
0

I would use sed.

ls *.alarms | sed 's/[0-9][.]alarms//'
ddoxey
  • 2,013
  • 1
  • 18
  • 25
  • 2
    Parsing the output of `ls` is not an recommendable practice ^^ – Léa Gris Aug 05 '19 at 12:57
  • Yes, I see. I've had scripts break because of parsing ls which is including ANSI markup for coloration. Ugh, so annoying. Because of this I'll generally use the --colors=never option. – ddoxey Aug 06 '19 at 23:14