Ubuntu: Bash: changing file extentions of all files in a directory and copying odd lines



Question:

How would one go about taking all the *.txt files in a given folder (users input) and copying odd lines to files with identical names but different extension (bat/html or anything else)

I assume cp or mv wont work, something like sed should do the trick for lines, but im having a hard time incorporating everything together.

If anyone could help me piece this together I would be very thankful

#!/bin/bash  clear    #seems like a good idea to get a full path to the directory im gonna be working in, not #sure how to go about it though.     path=pwd    #getting users input    read Directory    #check if said directory exists  if[ -d $Directory]; then  #if it does  #all files with .txt extention are to be copied   for *.txt in $(ls)  do  mv *.txt *.bat    #aaand now im lost, didnt have a chance to even test this, since i have linux only in #my studying enviroment (uni), will get on my personal PC later on  #something like sed could/should work in there, but i have no idea how to go about it    #if doesnt  else  echo "Directory does not exist or you do not have a permission to alter its contents"  


Solution:1

#!/bin/sh   cd "$1" || { echo "Couldn't cd to directory $1.  Quitting." ; exit 1 ; }   for fname in *.txt  do      awk 'NR % 2 == 1 { print; }' "$fname" >"${fname%.txt}.bat"  done  

Put the above in a file and make the file executable (chmod +x yourfilename). Now, run this command with the directory that you want to operate on as the first argument.

The script changes to the directory you request (cd "$1"). If that fails (the directory doesn't exist), then the script exits with an error message. If cd "$1" succeeds, then the script goes through each .txt file in the directory, selects the odd lines (NR % 2 == 1) and writes them to a file with same name except with extension ".bat".


Solution:2

Not sure what you mean by "odd lines"[1], but this statement achieves just what your code currently attempts to do:

cd "$1" && rename 's/\.txt$/.bat/' *.txt  

No need to do your own error messages, the shell will do them just fine.

[1] This makes it sounds a lot like a Uni homework assignment.


Solution:3

Thank you to all that have replied, you have helped me greatly in gaining some understanding of bash scripting, now that this question is resolved, how would one go about closing a question?

I used script provided by John1024, worked flawlessly. Very thanful for that. Cheers

!/bin/sh

cd "$1" || { echo "Couldn't cd to directory $1. Quitting." ; exit 1 ; } for fname in *.txt do awk 'NR % 2 == 1 { print; }' "$fname" >"${fname%.txt}.bat" done


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »