-2

So I am a bit of a noob and have a problem at work. There is a program outputs names in a ie

apple
banana
orange
P1n34ppl3

The problem is that the files that correspond to that (separate program) are just in 1.txt 2.txt and so on. Is there a way to iterate through the files in a given directory renaming them to the names in the text file using just the core utils ie mv, ls, grep, awk, sed. The system is a standalone RHEL box that is kind of old and no way to get patches or connect to repos with new programs.

3
  • 2
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Commented Jun 15, 2023 at 23:33
  • What have you tried and where is it not working? It's fine to ask for help but it's also important to give an effort. Commented Jun 16, 2023 at 0:05
  • 1
    The task you want to accomplish should be feasible with standard tools, but it's not clear what precisely you want to achieve. You seem to say that 1.txt should be renamed to apple, 2.txt to banana and so on. Is that correct? If so, loop over the output of the program and count the text files, e.g. i=1; for file in $(program); do mv $i.txt $file; i=$((i+1)); done. Commented Jun 16, 2023 at 0:48

1 Answer 1

1

Assuming there are as many non-hidden files in the current working directory as there are lines in the output of your-program and that none of the names of the files contain newline characters, you could do in a shell with support for ksh-style process substitution (ksh, zsh, bash):

paste -d '\n' <(ls -v) <(your-program) | xargs -rn2 -d '\n' echo mv --

(and remove the echo if that looks OK).

ls with -v sorts numerically so that for instance 10.txt comes between 9.txt and 11.txt instead of between 1.txt and 2.txt with the normal lexical order.

paste zips the lines of ls and those of your-program.

xargs gets two lines at a time to pass to mv.

-v, -r, -d are GNU extensions, but your system should have GNU utilities.

If you have zsh, you can do it a lot more reliably with:

files=( *(Nn) ) # or *.txt(Nn) or <->.txt(Nn) for number.txt only
lines=( ${(f)"$(your-program)"} )
for old new (${files:^lines}) echo mv -- $old $new

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.