I'm trying to rename all files that start with an "m" to be the same name except with the first character (or "m" in this case) stripped away.
My strategy is to:
- List all the files, with
ls
- Filter for the ones I want, with
egrep
- Generate the string I don't want next to the one I want, separated by a space, with
awk
, for example,mfoo foo
- Feed into
xargs
tomv mfoo foo
Some questions:
- Is this a good strategy?
- What is a better one?
I'm stuck on Step 3, below is how I've approached the problem.
I'm working in the following directory:
$ find .
.
./cat
./mbar
./mbaz
./mfoo
I'm able to quickly get 1-2:
$ ls | egrep '^m'
mbar
mbaz
mfoo
Step 3 is more difficult. I used gsub
to generate the second string I want, but I'm not sure how to "stick it together with the original value separated by a space":
$ ls | egrep '^m' | awk '{ gsub(/^./, ""); print }'
bar
baz
foo
Step 4 by it's makes sense to me, although I'm not sure how to finish Step 3 so I can't finish it yet. Below is one example of how I think it should work:
$ echo mfoo foo | xargs mv
$ find .
.
./cat
./foo
./mbar
./mbaz
I think I'm close I just need to find out how to save the old value and print it next to the gsubed value. I've tried the following small example but it's not working:
$ echo mfoo | awk '
pipe quote> { old = $0 }
pipe quote> { new = gsub(/^./, "") }
pipe quote> { print $old " " $new }'
awk: illegal field $(mfoo), name "old"
input record number 1, file
source line number 4
- How do I make a substitution to
$0
but save the old value? - Why am I getting this error?
awk
? I'm learning how to use it so I was excited to use it but I also thought it was an appropriate time to use it. – mbigras Apr 09 '17 at 21:31ls
’s output is not a good idea, and using AWK for simple string processing is overkill. – Stephen Kitt Apr 09 '17 at 21:35Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unified focus. Some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. This results in inconsistent command syntax and overlap of functionality, not to mention confusion.
It seems like starting off by just learningawk
andsed
for string manipulation is a better idea, no? – mbigras Apr 09 '17 at 23:56