如何使用SED / AWK将文本文件中的第一行与最后一行交换

时间:2018-07-20 10:21:05

标签: unix awk sed

我正在尝试在UNIX中的文本文件中将第一行与最后一行交换 文件具有:

line1
line2
line3
line4
line5
line6

我想要这样:

line6 
line2
line3
line4
line5
line1

我正在使用sed -n -e '1 s/^.*$/$p' file。这没有发生。

6 个答案:

答案 0 :(得分:1)

EDIT2: 根据Ed ir先生的评论,在此处也添加了此解决方案,这在第二行为空的情况下更适用,也可以使用。

awk 'NR==1{first=$0;next} NR>2{val=val prev ORS} {prev=$0} END{print prev ORS val first}  Input_file

编辑: :仅交换第一行和最后一行可能对您有所帮助(考虑到您的Input_file与所示示例相同)。

awk 'FNR==1{first=$0;next} {val=(val?val ORS prev:prev?$0:"")} {prev=$0} END{print $0 ORS val ORS first}' Input_file

说明:

awk '
FNR==1{                            ##Checking if line is first line then do following.
  first=$0;                        ##Creating varable first whose value is current line value.
  next                             ##next will skip all further statements from here.
}
{
  val=(val?val ORS prev:prev?$0:"")  ##Creating variable named val here whoe value is concatenating to its own value with variable prev value.
}
{
  prev=$0                          ##Creating variable prev whose value will be current value of line but will become previous value for next line.
}
END{
  print $0 ORS val ORS first       ##Printing current line ORS val ORS and first here.
}'  Input_file                     ##Mentioning Input_file name here.

能否请您尝试以下操作,如果有帮助,请告诉我。

awk -v from=1 -v to=6 'FNR==from{source=$0;next} FNR==to{target=$0;next} {val=val?val ORS $0:$0} END{print target ORS val ORS source}' Input_file

答案 1 :(得分:1)

这可能对您有用(GNU sed):

$(function () {
    var $mainSliderWrap = $('#slider_main_wrapper')
        , $sliderMain = $mainSliderWrap.find('.main-slider')
        , $sliderchildren = $sliderMain.children('li')
        , $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
    // Slider Setup
    window.addEventListener('resize', initMainSlider);
    initMainSlider();

    // Slider SetUp function
    function initMainSlider() {
        var wWidth = window.outerWidth
            , sliderMainWidth = wWidth * $sliderchildren.length
        $sliderMain.css('width', sliderMainWidth + 'px');
        $sliderMain.children('li').first().addClass('visible');
        $sliderIndicator.children('li').first().addClass('active');
    }
    // Want to Run Slider on Click event
    $sliderIndicator.on('click', 'li', updateMainSlider);
    // If Click Event Not happenening then I want to auto run Slider after 5 seconds
    var go = autoRun();
    // start autoRun
    go();
    var interval;

    function autoRun() {
        var mainSliderChildLenght = $sliderchildren.length;
        var i = 0;
        var next = true;
        var dir;
        return function() {
            setInterval(function () {
                if (mainSliderChildLenght == i || i < 0) {
                    next = !next;
                    if (i < 0) {
                        i = 0;
                    }
                }
                if (next) {
                    dir = 'next';
                    i++;
                }
                else {
                    dir = 'prev';
                    i--;
                    if(i < 0) {
                        return
                    }
                }
                updateMainSlider(dir);
                $('#result').text(i)
            }, 5000);
        });
    }
    // Here is the function for Updating the Slider
    function updateMainSlider(a) {
        var visibleSlide = $sliderchildren.filter('.visible')
            , actualTranslate = getTranslateValue($sliderMain, 'X');
        if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
            console.log(a)
            var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
                , newSlideOffsetLeft = newSlide.offset().left
                , valueToTranslte = -newSlideOffsetLeft + actualTranslate;

            setTranslateValue($sliderMain, 'translateX', valueToTranslte);

            visibleSlide.removeClass('visible');
            newSlide.addClass('visible');
            $sliderIndicator.children('.active').removeClass('active');
            $sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
        }
        else { // inside this if is running when function is called from click event
            clearInterval(interval);
            console.log(a)
            var newSlide = $(a.target)
                , $newSlideIndicatorIndex = newSlide.index()
                , $visibleSlideIndex = visibleSlide.index();
            if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
                $($sliderIndicator).addClass('disable-click');
                setTimeout(function () {
                    $($sliderIndicator).removeClass('disable-click');
                }, 1000);
                var diff = $newSlideIndicatorIndex - $visibleSlideIndex
                    , valueToTranslte = -(diff * window.outerWidth) + actualTranslate;

                setTranslateValue($sliderMain, 'translateX', valueToTranslte);

                $($sliderchildren[$visibleSlideIndex]).removeClass('visible');
                $($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
                $sliderIndicator.children('.active').removeClass('active');
                $sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
            } // end if
            go();
        } // end else
    } // end function
    // SetTranslate Value Fucntion
    function setTranslateValue(element, property, value) {
        $(element).css({
            'transform': property + '(' + value + 'px)'
        });
    }
    // Get Translate Value function
    function getTranslateValue(element, axis) {
        var trValue = $(element).css('transform');
        if (trValue !== 'none') {
            trValue = trValue.split(')')[0];
            trValue = trValue.split(',');
            trValue = (axis == 'X') ? trValue[4] : trValue[5];
        }
        else {
            trValue = 0;
        }
        return Number(trValue);
    }
})

将整个文件复制到保留空间(HS),并在最后一行之后,交换到HS,将文件拆分为第一行,中间和最后一行,并替换第一行和最后一行。

两遍替代解决方案:

sed 'H;$!d;x;s/\n\([^\n]*\)\(\n.*\n\)\(.*\)/\3\2\1/' file

创建sed脚本,将第一行更改为最后一行,将最后一行更改为第一行。

使用猫,头,尾巴和sed的另一种解决方案:

sed -n '1s/.*/$c&/p;$s/.*/1c&/p' file | sed -f - file

答案 2 :(得分:0)

在sed中,您需要进行两次通过;改用ed可能更有意义。然后,我们只需要两个 m 命令-将最后一行移到第一行之后,然后将第一行移到末尾:

$m1
1m$

演示

#!/bin/bash

set -euo pipefail

# Create our input file

file=$(mktemp)
trap 'rm "$file"' EXIT

cat >"$file" <<END
line1
line2
line3
line4
line5
line6
END

echo Before:
cat "$file"
echo

# Make the change

ed -s "$file"  <<<$'$m1\n1m$\nwq'

# Show the result

echo After:
cat "$file"

如果需要编写其他输出文件,当然可以照常向wq命令添加文件名参数。

答案 3 :(得分:0)

仅在headtailsed的单线混合情况下:

$ FIRST=$(head -1 file.txt) LAST=$(tail -1 file.txt) \
sed "1 s/^.*$/${LAST}/" file.txt | sed "$ s/^.*$/${FIRST}/"

答案 4 :(得分:0)

对于非常大的文件,您可能会对两次通过感兴趣:

awk '(NR!=FNR){print (FNR==1 ? t : (FNR==c ? h : $0) ); next }
     (NR==1){h=$0}{t=$0;c=NR}' file file

答案 5 :(得分:0)

使用sponge util

if($row && $row['useremail']==$useremail && $row['password']==$password){
    header('refresh:1;dashboard.php');
    echo $success='Login Successful';
} else{
    echo 'Login Failed';
}