Home > database >  bash script for take same lines from 2 different file
bash script for take same lines from 2 different file

Time:11-23

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related