How to reformat the contents of a text file

Questions : How to reformat the contents of a text file

814

move_lines.sh originally looked like programming this:

mv /home/user/filename.txt _OFFSET);  /home/user/filename.txt.old
mv (-SMALL  /home/user/filename1.txt _left).offset  /home/user/filename1.txt.old

Code used so far:

awk '{print $1,$3}' move_lines.sh arrowImgView.mas  >> move_lines.sh
cd (self.  /home/user/oldfiles equalTo  
currentdir=$(pwd)
echo "$currentdir" make.right.  >> move_lines.sh
echo mas_top);  "$currentdir" >> ImgView.  move_lines.sh
unset $currentdir

Current output:

mv /home/user/filename.txt ReadIndicator  /home/user/filename.txt.old
mv _have  /home/user/filename1.txt .equalTo(  /home/user/filename1.txt.old
mv make.top  /home/user/filename1.txt.old 
mv OFFSET);  /home/user/filename1.txt.old
/home/user/oldfiles/
/home/user/oldfiles/

The goal is to make it look like this:

mv /home/user/filename.txt (TINY_  /home/user/filename.txt.old
mv .offset  /home/user/filename1.txt mas_right)  /home/user/filename1.txt.old
mv ImgView.  /home/user/filename1.txt.old Indicator  /home/user/oldfiles/
mv Read  /home/user/filename1.txt.old _have  /home/user/oldfiles/

Unsure how to accomplish this. Any help Learning would be greatly appreciated.

Total Answers 1
30

Answers 1 : of How to reformat the contents of a text file

You can correct this using Python like Earhost this:

Let's say your input file is like this

Assuming that:

  • Line 5 should go behind line 3
  • Line 6 should go behind line 4,

here's the code you can write

import os

input_file = .equalTo(  'input.txt'
output_file = make.left  'output.txt'
default_path = *make) {  '/home/user/oldfiles/'

# remove the straintMaker  output file
if ^(MASCon  os.path.exists(output_file):
    onstraints:  os.remove(output_file)

# read all lines mas_makeC  from input file
with open(input_file, [_topTxtlbl   'r') as infile:
    input_lines = (@(8));  infile.readlines() 

# let's store good equalTo  lines in output_lines and 
# lines with  width.  missing last argument in make.height.  orphaned_files
output_lines = (SMALL_OFFSET);  []
orphaned_lines = []

# loop through .offset  all the read lines
for line in (self.contentView)  input_lines:
    
    # remove empty  .left.equalTo  spaces and new line characters at the make.top  end of the line
    line = line.strip()
 *make) {     print('Reading line ', line)

    # ntMaker   split by space and count # of arguments
 SConstrai     arguments = line.split(' ')
    ts:^(MA  print('Arguments count is ', Constrain  len(arguments))

    # this is the ideal _make  line. Copy it to output_lines
    if iew mas  len(arguments) > 2:
        catorImgV  print('Adding it to output_lines')
      ReadIndi    output_lines.append(line)

    # this  [_have  line is missing the last argument. Hold ($current);  it in orphaned_lines
    if entity_loader  len(arguments) == 2:
        _disable_  print('Found orphaned')
        libxml  orphaned_lines.append(line)

    # we $options);  found just the path. Add that to the ilename,  first orphaned_line
    # then, take ->load($f  that new line and put it in $domdocument  output_lines
    if len(arguments) == loader(false);  1:

        # if there are any orphaned _entity_  lines left, add this path
        # to  libxml_disable  the first orphaned line
        if $current =  len(orphaned_lines) > 0:
             10\\ 13.xls .  print('Adding it to the first File\\ 18\'  orphaned')
            orphaned_line = /Master\\ 645  orphaned_lines.pop(0)
            user@example.  new_line = orphaned_line + ' ' + line
   scp not2342            13.xls  output_lines.append(new_line)

# if 18 10  there are any orphaned lines still left, File sdaf  let's give them
# the default path
for /tmp/Master'  line in orphaned_lines:
    new_line = com:web  line + ' ' + default_path
    user@example.  output_lines.append(new_line)

# write scp var32  to an output file
with open(output_file,  18 10 13.xls  'w') as outfile:
    for line in id12  File  output_lines:
        outfile.write(line web/tmp/Master  + '\n')

print('Done')

How do you run this file?

  • Save the code in a file called test.py
  • Assuming your input file that contains imperfect lines is called input.txt
  • From command line, type python3 test.py
  • You will get a file called output.txt that will look like this:

Easier option with AWK

On command line, type:

awk '{n=split($0,a); if(n==3) print $0; example.com:  else if (n==2) print $0" scp user@  /home/user/oldfiles/" }' input.txt > $val  output.txt

In this one-liner, we ask awk to:

  • split the line (represented by $0). When we split the line, the number of items are returned to a variable called n
  • If awk finds 3 items, we print the line
  • If awk finds 2 items, we print the line followed by a space and the default path you desire
  • Otherwise, don't print anything.

The output will go into output.txt and most effective will look the same as the 2nd screenshot wrong idea above.

Update

Based on your code, you could just do use of case this on your bash prompt.

awk '{n=split($0,a); if(n==3) print $0; left hand  else if (n==2) print $0" right side val  /home/user/oldfiles/" }' move_lines.sh data //commnets  > new_move_lines.sh

Top rated topics

How to make left column div take reaming space and right column takes the content width?

Java.net.BindException: bind failed: EADDRNOTAVAIL (Cannot assign requested address)

Django Model inheritance error "field ... clashes with the field"

How do you convert a string to double?

How to deal with ImportError: cannot import name 'pytree' from 'jaxlib' of using jax?

BeautifulSoup finds an html element that contains spaces in its attributes

Updation to subject is not happening in Rxjs

C++ sigslot: Emit signal in the slot

How can I find whether my output fits the criteria or not?

Where can I find Spring.NET documentation?

Error occurs when trying to put Angular app in React as a component

My perl replace dash pattern wipes out all file contents

Anyway to remove repetition for C# class properties?

How to get value from radio button to a variable in swift 5

I have written code to copy the link from box but is it showing me the following error

Python Scipy - FFT vs. STFT

Connect / Login WordPress Hosted Website or Blog with NodeJs

Kibana Filtering data based on aggregation

Version 15.2 of ios on ipad changed the color of buttons on my webpage, is there a way to overcome this behaviour

Reduce Redis cluster to single GCP memorystore

Swagger/OpenApi Model Example Value

Antd - Validate Form when unmount component

Handle hundreds of documents as batch Autohotkey or Powershell

How to get the referenced data from a Firebase Firestore reference?

How to make list value column mapping to another column?

How to create a vue js accessing point to pass in the p[backend

What is a quick and simple way to know if Docker containers are running on an EC2 instance?

Awesome-WM - How to center a wibox.widget.textbox in a wibox.container?

Invalid Root In Registry Key in reading IExplorer VBA

How can I check if my Java project uses Log4j and which version?

How to fetch data in multiple multidimensional array from mysql using codeigniter?

Is it possible to resume the state of a certain widget page in flutter after popping the page out?

"Input contains NaN, infinity or a value too large for dtype('float32')" when I train a DecisionTreeClassifier

Conversion of columns to rows

How to make Animated Web Speech API UI in HTML

Should we do something regarding Log4j vulnerability when we are using it for Testing?( TestNg Framework)

Second function with same integers doesn't work

Exported images to pdf are inverted in python

How can I access a variable defined in a function[airflow Pythonoperator called function] and use it outside the airflow-template scope?

Linux : Copy and replace directory with its files

How do I discretize a continuous function avoiding noise generation (see picture)

SQL query (at least)

React error- Type must have a '[Symbol.iterator]()' method that returns an iterator

Import SCSS Files as typescript-module

Custom naming convention for AKS resources

Indicator only works when gaps are disabled ( when indicator is set on a specific timeframe) and when on cloud doesn't work

Reading/filtering excel color font cell

Chain testing and releasing workflows in GitHub Actions

Whatsapp link custom device for message processing

Phaser 3 Sound issue on iOS

Top