1

I have a directory users which is full of folders named for each user. Within those folders, there is a file called userinfo.csv which I would like to pull out of the folder and into the users. Since every file in the user folder is called userInfo, I want to rename it to include the username which is in the folder. I tried the following but it doesn't work because the username in $dir is the full directory. I'm not that attached to renaming it to the username, I just need to rename it something so that when it moves into users I won't be left with just one file and a bunch of errors.

How can I improve this?

# for every subdirectory, copy userinfo.csv to /users and rename to avoid confusion/errors
for dir in /path/to/users/*/; do
    (
        cd "$dir" && cp userinfo.csv _$("dir").csv && cp _$("dir").csv /path/to/users/
    )
done
6
  • 1
    That specific error suggests that the editor you wrote the script in added Windows-style (CRLF) line endings Jun 7, 2019 at 15:52
  • good catch, thank you. though even once I fix that, it still doesn't do what I want. I've edited my question to clarify this. Jun 7, 2019 at 15:57
  • Is the location of the userinfo.csv file identical relative to each user? Is it always /path/to/users/*/userinfo.csv or it can be at any depth under the /path/to/users/ folder?
    – deimos
    Jun 7, 2019 at 15:59
  • 1
    What do you think $("dir") does?
    – choroba
    Jun 7, 2019 at 15:59
  • @deimos yes it will always be /path/to/users/*/userinfo.csv and @choroba I now realize that $("dir") is the full directory so of course renaming it as such wouldn't have worked. Jun 7, 2019 at 16:01

2 Answers 2

1

If you don't need the username in the final filename, would

for i in /path/to/users/*/userinfo.csv ; do
  mv $i /path/to/users/userinfo-$RANDOM.csv
done

do the trick for your use-case ?

If not, you can also use bash's parameter substitution:

for i in /path/to/users/*/userinfo.csv ; do
  mv $i /path/to/users/${i//\/-}
done

This will replace all / with - in the variable $i (path+filename). So you'll end up with, for example:

/path/to/users/path-to-users-john-userinfo.csv
/path/to/users/path-to-users-jack-userinfo.csv
0
1
for i in $(ls -1 /path/to/users/); do
    mv /path/to/users/$i/*/userinfo.csv /path/to/users/userinfo_$i.csv
done

This will work assuming the userinfo.csv location is /path/to/users/$user/userinfo.csv. In cases when /path/to/users/ contains folders with no userinfo.csv or just files, mv won't do anything and therefore can be ignored.

The $i in this case will contain the name of each item in /path/to/users/ be it a file or a folder.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .