skip to Main Content

I’ve for example file called users and it’s include

user1
user2
user3

and file called newusers including:

newuser1
newuser2
newuser3

and now I need bash script for take user1 and newuser1 and do some command for example ‘mv user1 to newuser1’ and etc.
something like this but this is not working for me:

user=cat users
newuser= cat newusers

for u in user ; for n in newuser; do mv $u $n done; done

2

Answers


  1. If you nest the two loops, you get "number of users" * "number of newusers" move operations. But you want only "number of users" move operations.

    Pure Bash:

    #! /bin/bash
    
    exec {users}<users
    exec {newusers}<newusers
    
    while true; do
      read user <&$users || exit
      read newuser <&$newusers || exit
      mv "$user" "$newuser"
    done
    
    Login or Signup to reply.
  2. Provided the files are in matching order, and the same number of lines:

    tab=$(printf 't')
    
    paste users newusers |
    while IFS=$tab read user newuser; do
        echo "move $newuser $user"
    done
    

    It works in bash or sh. You can build a command using the corresponding lines. The lines can’t already contain tabs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search